import { defineStore } from 'pinia';
import { ref } from 'vue';

export const useBarrageStore = defineStore('barrage', () => {
  const barrageOn = ref(false);
  const colors = ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#00FFFF', '#FF00FF'];
  const barrageTexts = ['Hello', 'World', 'Vue3', 'Barrage', 'Example', 'Switch'];
  const barrages = ref([]);
  let intervalId: number | null = null;

  const setBarrage = (value: boolean) => {
    barrageOn.value = value;
    if (value) {
      startBarrage();
    } else {
      stopBarrage();
    }
  };

  const startBarrage = () => {
    intervalId = window.setInterval(() => {
      const newBarrages = barrageTexts.map(text => ({
        text,
        color: getRandomColor(),
        top: getRandomTop(),
        left: window.innerWidth,
        speed: getRandomSpeed(),
      }));
      barrages.value.push(...newBarrages);
    }, 1000);
  };

  const stopBarrage = () => {
    if (intervalId !== null) {
      clearInterval(intervalId);
      intervalId = null;
    }
    barrages.value = [];
  };

  const getRandomColor = () => {
    return colors[Math.floor(Math.random() * colors.length)];
  };

  const getRandomTop = () => {
    return Math.floor(Math.random() * (window.innerHeight - 50));
  };

  const getRandomSpeed = () => {
    return Math.random() * 2 + 1; // 随机速度在1到3之间
  };

  const updateBarrages = () => {
    barrages.value.forEach(barrage => {
      barrage.left -= barrage.speed;
    });
    barrages.value = barrages.value.filter(barrage => barrage.left > -200);
  };

  return {
    barrageOn,
    colors,
    barrageTexts,
    barrages,
    setBarrage,
    updateBarrages,
  };
});
